//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/13.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    var userAccount : UserAcount?
    
    override init() {
        
        userAccount = UserAcount.loadUserAccount()
        
        super.init()
    }
    
    var userLogin : Bool {
        return userAccount?.access_token != nil
    }

    var token : String? {
        return userAccount?.access_token
        
    }
    
    var userName : String? {
    
    return userAccount?.name
        
    }
    
    var headImageURL: NSURL? {
        return NSURL(string: userAccount?.avatar_large ?? "")
        
    }
    
    func loadAccessToken(code: String , finished : (isSuccess : Bool) -> () ){
        let urlString = "oauth2/access_token"
        
        let parameters = ["client_id" : client_id , "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString : urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            let account = UserAcount(dict: dict!) 
            
            self.loadUserInfo(account, finished: finished)

         
        }
 
    }
    
    
    private func loadUserInfo(account : UserAcount, finished : (isSuccess : Bool) -> ()){
        
        let urlString = "2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameters = ["access_token" : account.access_token!,"uid" : account.uid!]
        
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            let name = dict!["name"] as! String
            let avatar_large = dict!["avatar_large"] as! String
            account.name = name
            account.avatar_large = avatar_large
            
            print(account)
            account.saveAccount()
            finished(isSuccess: true)
         }
        
        
    }
    
    
    
}
